<template>
    <view class="content">
        <!-- 生成训练计划模块 -->
        <view class="not_train" v-if="not_train">
            <text class="title">
                还未曾训练过, 请点击下方按钮开始生成训练计划
            </text>
            <nut-button
                class="start_button"
                type="primary"
                @click="createTrainPlan"
            >
                点我去生成训练计划</nut-button
            >
        </view>

        <view v-if="!not_train && !all_done" class="today_train">
            <text v-if="today_done" >今日训练已完成</text>
            <view v-if="!today_done" class="title">开始今日训练</view>

            <view> 课程: {{today_train['plan']}} </view>
            <view> 阶段: {{today_train['month']}} </view>
            <view> {{today_train['week']}}</view>
            <view> 第{{today_train['day']}}天</view>
            <view>今日课程: </view>
            <view
                class="course"
                v-for="course of today_courseS"
                :key="course.idx"
            >
                <text>{{ course["title"] + "(" + course["name"] + ")" }}</text>
                <text class="desc">长按下方网址复制,然后在浏览器中打开</text>
                <text selectable="true" class="link">{{ course["link"] }}</text>
            </view>
            
            <text>已训练进度</text>
            <nut-progress :percentage="percentage" stroke-color="pink"></nut-progress>

            <nut-button
                :disabled = "today_done"
                block
                type="success"
                class="train_complete"
                @click="trainComplete"
                >{{complete_button_txt}}</nut-button
            >
        </view>

        <view  
            v-if="all_done"
            class="all_done"
        > 
            <!-- 完成了本计划的所有训练内容, 开始新的训练计划 -->
            <image
                style='width: 650rpx; height: 650rpx;'
                :src= "complete_jpg"
            />
            <text> 您已完成本计划所有训练, 您可以点击下方按钮生成新的训练计划, 或者直接退出本小程序</text>
            <nut-button
                block
                class="all_done_button"
                type="primary"
                @click="createTrainPlan"
            >
                点我去生成训练计划</nut-button
            >
        </view>


        <nut-dialog
            content="今天的课程不止一节, 确定都完成了吗?"
            v-model:visible="dialog_visiable"
            @cancel="onCancel"
            @ok="onOk"
        />
    </view>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from "vue";
import "./index.less";
import Taro from "@tarojs/taro";
import {
    LAST_POINT_KEY,
    TODAY_POINT_KEY,
    TRAIN_HISTORY_KEY,
    TRAIN_ALL_DONE,
} from "../../utils/constant";
import { getCourseByTrainPoint, getNextPointByLast, getTrainProgressByPoint } from "../../utils/tools";
import { eventCenter, getCurrentInstance } from "@tarojs/taro";
import * as dayJs from "dayjs";
const complete_jpg = require("../../assets/images/train_over.jpg")
const DATE_FORMAT = 'YYYY-MM-DD'

export default defineComponent({
    setup() {
        // 还未曾训练过的标识
        const not_train = ref(false);
        //训练计划
        const today_courseS = ref<any[]>([]);
        const dialog_visiable = ref(false);
        // 所有训练都已经完成
        const all_done = ref(false);
        // 训练百分比
        const percentage = ref(0);

        const today_done = ref(false);
        const  complete_button_txt = ref('完成今日所有训练并记录');

        
        let today_point: any;
        let today_train = ref({});
        //监听页面的onShow事件, 如果用once, 那么只绑定一次
        eventCenter.on(getCurrentInstance().router.onShow, () => {
            console.log("训练页面onShow");
            // 获取今日的训练计划
            today_point = Taro.getStorageSync(TODAY_POINT_KEY);
            // console.log("today_point---", today_point);
            if(today_point == TRAIN_ALL_DONE){
                // 如果所有的计划都完成了
                all_done.value = true;
            }

     
            

            //获取上一个训练点
            let  last_point = Taro.getStorageSync(LAST_POINT_KEY);
            // console.log("last_point---", last_point);
            if(last_point){
                let { complete_date  } = last_point;
                // console.log("complete_time---", complete_date);
                // let today = dayJs().format();
                // dayJs(complete_time).isToday() // true
                let today = dayJs().format(DATE_FORMAT);
                // console.log("today---", today);
                // console.log("complete_date---", complete_date);
                if(today == complete_date){
                    console.log("今天已经训练过");
                    complete_button_txt.value = '今天已经训练过'
                    today_done.value = true;
                }
            }

            console.log("today_point--", today_point);
            
            if (today_point) {
                // 根据训练起始点, 获取到训练课程, 并渲染到页面上
                // console.log("获取到数据---", today_point);
                // 今日的训练计划
                // 根据today_point获取训练进度
                percentage.value = parseFloat(getTrainProgressByPoint(today_point));
                let courses =  getCourseByTrainPoint(today_point);
                today_courseS.value =courses;

                today_train.value = today_point;
                // console.log("today_courses---", courses);
            } else {
                console.log("还未训练过----");
                not_train.value = true;
            }
        });

        const createTrainPlan = () => {
            // 跳转到生成计划页面
            Taro.redirectTo({
                url: "/pages/create/index",
            });
        };

        // 训练完成按钮被点击的时候
        const trainComplete = () => {
            // console.log("today_courseS", );
            if (today_courseS.value.length > 1) {
                // 弹出对话框二次确认
                dialog_visiable.value = true;
            } else {
                // 直接完成并生成记录
                onOk();
            }
        };

        const onOk = async() => {
            //生成任务记录,
            // 记录时间,  计划名称,  month, week, day  , 即可
            // console.log("today_point---",today_point);
            let training_history = Taro.getStorageSync(TRAIN_HISTORY_KEY);
            let today = dayJs().format(DATE_FORMAT);
            let courses = today_courseS.value.map((c) => {
                return `${c.title}(${c.name})`;
            });

            // 把今天的内容放到历史记录中,并生成下一个训练计划
            let train_his = {
                time: today,
                plan: today_point["plan"],
                courses,
            };
            // 记录上一个训练点
            let last_point = Object.assign({
                ...today_point,
                complete_date: today,
            });
            Taro.setStorageSync(LAST_POINT_KEY, last_point);
            // 根据刚训练完成的记录, 生成下一个训练内容
            let new_point = await getNextPointByLast(last_point);
            // console.log("获取到的new_point---", new_point);
            Taro.setStorageSync(TODAY_POINT_KEY, new_point)

            // console.log("training_history---",  training_history);
            // console.log("train_his---", train_his)
            //生成历史记录
            let his: any[] = [];
            if (training_history) {
                // 解析以前的计划
                his = training_history;
            }
            //今日计划放到记录中
            his.unshift(train_his);
            Taro.setStorageSync(TRAIN_HISTORY_KEY, his);
            // 最后, 修改页面内容
            complete_button_txt.value = '今天已经训练过'
            today_done.value = true;
        };
        const onCancel = () => {
            console.log("取消dialog");
        };
        return {
            not_train,
            createTrainPlan,
            today_courseS,
            trainComplete,
            dialog_visiable,
            onOk,
            onCancel,
            complete_jpg,
            all_done,
            percentage,
            today_done,
            complete_button_txt,
            today_train
        };
    },
});
</script>